﻿using AutoMapper;
using Basic.Traceability.Domain.DeepProcessing;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.DeepProcessing.DeepProcessingEnterpriseInformation;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.DeepProcessing.DeepProcessingEnterpriseInformation
{
    public class CreateDeepProcessingEnterpriseInformationHandler : IRequestHandler<CreateDeepProcessingEnterpriseInformationCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DeepProcessingEnterpriseInformationModel> _deepProcessingEnterpriseInformationRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateDeepProcessingEnterpriseInformationHandler> logger;

        public CreateDeepProcessingEnterpriseInformationHandler(IBaseRepository<DeepProcessingEnterpriseInformationModel> deepProcessingEnterpriseInformationRepository, IMapper mapper, ILogger<CreateDeepProcessingEnterpriseInformationHandler> logger)
        {
            _deepProcessingEnterpriseInformationRepository = deepProcessingEnterpriseInformationRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加深加工企业信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateDeepProcessingEnterpriseInformationCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<DeepProcessingEnterpriseInformationModel>(request);
            model.Id = YitIdHelper.NextId();
            var r = _deepProcessingEnterpriseInformationRepository.Create(model);
            if (r > 0)
            {
                res.Msg = "添加深加工企业信息成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                logger.LogInformation("添加深加工企业信息成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "添加深加工企业信息失败";
                res.Code = APIEnums.Fail;
                res.Data = r;
                logger.LogError("添加深加工企业信息失败");
                return Task.FromResult(res);
            }
            
        }
    }
}
